package org.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UploadService {
    private final RestTemplate restTemplate = new RestTemplate();

    public String uploadFileToSubBackend(MultipartFile file) {
        String url = "http://localhost:8089/netshop/upload/uploadAvatar"; // 子后端上传接口地址

        try {
            // 转成 ByteArrayResource（模拟文件上传）
            ByteArrayResource fileAsResource = new ByteArrayResource(file.getBytes()) {
                @Override
                public String getFilename() {
                    return file.getOriginalFilename(); // 返回文件名
                }
            };

            // 构造请求体，表单形式，key 要是 "file"
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", fileAsResource);

            // 设置请求头为 multipart/form-data
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            // 包装请求体和请求头
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

            // 发送 POST 请求
            ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);

            // 返回子后端响应
            return response.getBody();

        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败：" + e.getMessage();
        }
    }
}
